/*
 * Query button panel
 */
package gui;

import Protocol.PacketFactory;
import Protocol.PacketTypeKeeper;
import Protocol.QueryRequestPacket;
import Protocol.QueryResponsePacket;
import config.Content;
import handler.PanelController;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JPanel;

/**
 * This is the panel that holds the query buttons (The vertical menu)
 * @author Kay van Bree
 */
public class QueryButtonPanel extends JPanel {
	
	private PanelController panelController;
	
	/**
	 * This sets layout and gaps for the Query menu
	 * @author Kay van Bree
	 */
	public QueryButtonPanel(PanelController panelController){
		this.panelController = panelController;
		setPreferredSize(new Dimension(250, 500));
		FlowLayout layout = new FlowLayout();
		layout.setVgap(0);
		layout.preferredLayoutSize(this);
		setLayout(layout);
	}
	
	/**
	 * resets the QueryButtonPanel
	 * @author Kay van Bree
	 */
	public void reset(){
		removeAll();
		updateUI();
		populate();
		updateUI();
	}
	
	public void populate(){
		populate(false);
	}
	
	/**
	 * Create the buttons of this menu
	 * @author Kay van Bree, Joep Kemperman
	 * @param reload Reloads the buttons if true
	 */
	public void populate(boolean reload){
		// Is is a reload?
		if(reload == true){
			Content.log.println("Reloading query buttons...");
		} else {
			Content.log.println("Loading query buttons...");
		}
		
		// Create, communicate and receive the query packet
		QueryResponsePacket response = null;
		try {
			QueryRequestPacket request = (QueryRequestPacket) PacketFactory.getPacket(PacketTypeKeeper.QUERYREQUESTPACKET);
			request.setQuery("SELECT * FROM [dbo].BunieQuery;");
			response = (QueryResponsePacket) Content.connection.communicate(request);
			
			for (String[] row : response.getListWithAccounts()) {
				QueryButton button = new QueryButton(row[1], row[2]);
				Dimension size = new Dimension(240, 25);
				button.setPreferredSize(size);
				button.setMinimumSize(size);
				button.setMaximumSize(size);
				button.addActionListener(panelController);
				add(button);
			}
		} catch (Exception ex) {
			Content.log.println("We could not get your buttons from them bastards!");
		}
	}
}
